﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BrnMall.Manager.Domain.Distribution;
using PetaPoco;

namespace BrnMall.Manager.Manager.Distribution
{
    /// <summary>
    /// 
    /// </summary>
    public static class DistributorManager
    {
        #region 分销等级设置
        /// <summary>
        /// 
        /// </summary>
        /// <param name="grade"></param>
        public static int AddGrade(DisGrade grade)
        {
            using (var db = new QDMallDatabase())
            {
                var o=db.Insert(grade).ToString();
                var id = 0;
                int.TryParse(o, out id);
                return id;
            }
        }
        /// <summary>
        /// 获取分销商等级
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static DisGrade GetGrade(int id)
        {
            using (var db = new QDMallDatabase())
            {
                return db.SingleOrDefault<DisGrade>(id);
            }
        }
        /// <summary>
        /// 通过名称获取等级
        /// </summary>
        /// <param name="storeId"></param>
        /// <param name="name"></param>
        /// <param name="gradeType"></param>
        /// <returns></returns>
        public static DisGrade GetGrade(int storeId, string name,int gradeType)
        {
            using (var db = new QDMallDatabase())
            {
                return db.SingleOrDefault<DisGrade>(
                    "select top 1 * from dis_Grade where storeid=@0 and name=@1 and gradetype=@2"
                    , storeId, name, gradeType);
            }
        }

        /// <summary>
        /// 判断等级是否使用过
        /// </summary>
        /// <param name="storeId"></param>
        /// <param name="gradeId"></param>
        /// <returns></returns>
        public static bool CheckGradeIsUsing(int storeId,int gradeId)
        {
            using (var db = new QDMallDatabase())
            {
                var id = db.ExecuteScalar<int>("select isnull(count(GradeId),0) from dis_Distributor where storeid=@0 and gradeid=@1 ",storeId,
                    gradeId);
                return id > 0;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="grade"></param>
        public static void UpdateGrade(DisGrade grade)
        {
            if(grade.Id<0)return;
            using (var db = new QDMallDatabase())
            {
                db.Update(grade);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        public static int DeleteGrade(int id)
        {
            using (var db = new QDMallDatabase())
            {
                return db.Delete<DisGrade>(id);
            }
        }
        /// <summary>
        /// 获取默认等级
        /// </summary>
        /// <param name="storeId">店铺ID</param>
        /// <param name="gradeType">等级类型0分销商，1代理商</param>
        /// <returns></returns>
        public static DisGrade GetGradeDefault(int storeId, int gradeType)
        {
            using (var db = new QDMallDatabase())
            {
                var @default= db.SingleOrDefault<DisGrade>(
                    "select top 1 * from dis_Grade where storeid=@0 and isdefault=1 and gradetype=@1", storeId,
                    gradeType);
                if (@default != null) return @default;
                var t = new DisGrade
                {
                    IsDefault = true,
                    StoreId = storeId,
                    GradeType = gradeType,
                    Name = "初级",
                    Description = "默认等级"
                };
                db.Insert(t);
                return t;
            }
        }
        /// <summary>
        /// 设置当前等级为默认等级
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool SetGradeAsDefault(int id)
        {
            using (var db = new QDMallDatabase())
            {
                try
                {
                    var grade = GetGrade(id);
                    if (grade == null) return false;
                    db.BeginTransaction();
                    db.Execute("update dis_Grade set isdefault=0 where storeid=@0 and gradetype=@1", grade.StoreId,
                        grade.GradeType);
                    db.Execute("update dis_Grade set isdefault=1 where id=@0", id);
                    db.CompleteTransaction();
                }
                catch
                {
                    db.AbortTransaction();
                    return false;
                }
                
                return true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="storeId"></param>
        /// <param name="gradeType"></param>
        /// <returns></returns>
        public static IList<DisGrade> GetGradeList(int storeId, int gradeType)
        {
            List<DisGrade> result;
            using (var db =new QDMallDatabase())
            {
                result = db.Fetch<DisGrade>("select * from dis_Grade where storeid=@0 and gradeType=@1", storeId,
                    gradeType);
            }
            return result;
        }
        #endregion

        #region 分销设置

        public static DisConfig GetDisConfig(int storeId)
        {
            using (var db = new QDMallDatabase())
            {
                return db.SingleOrDefault<DisConfig>("select * from dis_Config where storeid=@0", storeId);
            }
        }

        #endregion

        #region 分销商管理
        /// <summary>
        /// 添加分销商
        /// </summary>
        /// <param name="dis"></param>
        /// <returns></returns>
        public static int AddDistributor(Distributor dis)
        {
            
            using (var db = new QDMallDatabase())
            {
                db.Insert(dis);
                return dis.Id;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dis"></param>
        public static void UpdateDistributor(Distributor dis)
        {
            using (var db = new QDMallDatabase())
            {
                db.Update(dis);
            }
        }
        /// <summary>
        /// 追加历史提现额度
        /// </summary>
        public static void AppendDistributorRequestBalance(int userid,decimal money)
        {
            if (userid < 0 || money < 0) return;
            using (var db = new QDMallDatabase())
            {
                db.Execute(
                    $"update dbo.dis_Distributor set RequestBalance=RequestBalance+{money} where userid={userid} AND isdelete=0");
            }
        }
        /// <summary>
        /// 获取下级分销商
        /// </summary>
        /// <param name="pid">上级代理商ID</param>
        /// <param name="rescure">是否递归</param>
        /// <returns></returns>
        public static IList<Distributor> GetChildDistributors(int pid, bool rescure)
        {
            using (var db = new QDMallDatabase())
            {
                var result=new List<Distributor>();
                if (!rescure)
                {
                    result= db.Fetch<Distributor>("select * from dis_Distributor where parentid=@0  AND isdelete=0", pid);
                }
                else
                {
                    var ids = db.Fetch<int>(@"with temp(id)
                                            as(
                                            select id from dbo.dis_Distributor where  parentid=@0  AND isdelete=0
                                            union all
                                            select a.id from dbo.dis_Distributor a inner join temp b on a.parentid=b.id
                                            )
                                            select * from temp", pid);

                    if (ids.Count <= 0) return result;
                    var sql = new StringBuilder();
                    sql.Append("select * from dis_Distributor where 1=1 ");
                    sql.AppendFormat(" and id in({0})", string.Join(",", ids));
                    result= db.Fetch<Distributor>(sql.ToString());
                }
                return result;
            }
        }
        /// <summary>
        /// 判断分销商是否是默认下线分销商
        /// </summary>
        /// <param name="id"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public static bool IsChildDistributor(int id, int parentId)
        {
            using (var db = new QDMallDatabase())
            {
                var ids = db.Fetch<int>(@"with temp(id)
                                            as(
                                            select id from dbo.dis_Distributor where status<>2 and parentid=@0  AND isdelete=0
                                            union all
                                            select a.id from dbo.dis_Distributor a inner join temp b on a.parentid=b.id
                                            )
                                            select * from temp", parentId);
                return ids.Contains(id);
            }
            
        }

        /// <summary>
        /// 更改分销商的代理商
        /// </summary>
        /// <param name="id"></param>
        /// <param name="agentId"></param>
        public static void UpdateDistributorAgent(int id, int agentId)
        {
            using (var db = new QDMallDatabase())
            {
                db.Execute("update dis_Distributor set agentid=@0 where id=@1  AND isdelete=0", agentId, id);
            }
        }

        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Distributor GetDistributor(int id)
        {
            using (var db = new QDMallDatabase())
            {
                return db.SingleOrDefault<Distributor>(id);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="storeId"></param>
        /// <returns></returns>
        public static void DeleteDistributor(int id,int storeId)
        {
            using (var db = new QDMallDatabase())
            {
                db.Execute("delete dis_Distributor where storeid=@1 and id=@0 ", id,storeId);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static Distributor GetDistributorByUserId(int userId)
        {
            using (var db = new QDMallDatabase())
            {
                return db.SingleOrDefault<Distributor>("select top 1 * from dis_Distributor where userid=@0  AND isdelete=0 ",
                    userId);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        public static void SetDistributorStatus(int id,int status)
        {
            using (var db = new QDMallDatabase())
            {
                db.Execute("update dis_Distributor set status=@1 where id=@0  AND isdelete=0", id,status);
            }
        }


        /// <summary>
        /// 获取当前店铺的所有分销商
        /// </summary>
        /// <param name="storeId"></param>
        /// <param name="gradeId">级别</param>
        /// <param name="orderTotalEnd"></param>
        /// <param name="page"></param>
        /// <param name="itemsPerPage"></param>
        /// <param name="disStoreName">分销商名称</param>
        /// <param name="orderTotalStart"></param>
        /// <returns></returns>
        public static Page<Distributor> GetDistributorList(int storeId,int gradeId,string disStoreName,int orderTotalStart,int orderTotalEnd, long page,long itemsPerPage)
        {
            using (var db = new QDMallDatabase())
            {
                var sql=new StringBuilder();
                sql.Append("select * from dis_Distributor where 1=1 and isagent=0  AND isdelete=0");
                if (storeId > 0)
                    sql.AppendFormat(" and storeid={0}", storeId);
                if (gradeId > 0)
                    sql.AppendFormat(" and gradeid={0}", gradeId);
                if (orderTotalStart > 0)
                    sql.AppendFormat(" and OrdersTotal>={0}", orderTotalStart);
                if (orderTotalEnd > 0)
                    sql.AppendFormat(" and OrdersTotal<={0}", orderTotalEnd);
                if (!string.IsNullOrEmpty(disStoreName))
                    sql.AppendFormat(" and disstorename like '{0}%'", disStoreName);
                return db.Page<Distributor>(page, itemsPerPage,sql.ToString());
            }
        }
        /// <summary>
        /// 获取分销商以及代理商信息
        /// </summary>
        /// <param name="storeId"></param>
        /// <returns></returns>
        public static IList<Distributor> GetAllDistributors(int storeId)
        {
            using (var db = new QDMallDatabase())
            {
                var sql = new StringBuilder();
                sql.Append("select * from dis_Distributor where 1=1  AND isdelete=0");
                if (storeId > 0)
                    sql.AppendFormat(" and storeid={0}", storeId);

                return db.Fetch<Distributor>(sql.ToString());
            }
        }
        /// <summary>
        /// 判断是否是分销商或者代理商
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public static bool CheckIsDistributor(int userid)
        {
            using (var db = new QDMallDatabase())
            {
                var dis=db.SingleOrDefault<Distributor>("select top 1 * from dis_Distributor where userid=@0 AND isdelete=0", userid);
                return dis != null;
            }
        }
        /// <summary>
        /// 设置分销商为代理商
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool SetDistributorAsAgent(int id)
        {
            using (var db = new QDMallDatabase())
            {
                try
                {
                    var dis = DistributorManager.GetDistributor(id);
                    db.BeginTransaction();
                    if (dis.IsAgent == 1) return true;
                    //找到分销商的所有下级分销商,无限极获取
                    var childDis = DistributorManager.GetChildDistributors(id, true);
                    foreach (var child in childDis)
                    {
                        if (child.ParentId == id)
                        {
                            child.ParentId = 0;
                            child.Path = child.Path.Remove(0, $"{id}|".Length);
                        }
                        else
                        {
                            child.Path = child.Path.Replace($"|{id}|", "|");
                        }
                        child.AgentDId = id;
                        DistributorManager.UpdateDistributor(child);
                    }

                    dis.ParentId = 0;
                    dis.Path = string.Empty;
                    dis.IsAgent = 1;
                    dis.DisLevel = 0;
                    dis.AgentDId = 0;
                    dis.GradeId = DistributorManager.GetGradeDefault(dis.StoreId, 1).Id;
                    DistributorManager.UpdateDistributor(dis);
                    db.CompleteTransaction();
                    return true;
                }
                catch
                {
                    db.AbortTransaction();
                    throw;
                }
                
            }
        }

        
        
        /// <summary>
        /// 获取当前店铺的所有代理商
        /// </summary>
        /// <param name="storeId"></param>
        /// <param name="gradeId">级别</param>
        /// <param name="orderTotalEnd"></param>
        /// <param name="page"></param>
        /// <param name="itemsPerPage"></param>
        /// <param name="orderTotalStart"></param>
        /// <returns></returns>
        public static Page<Distributor> GetDistributorAgentList(int storeId, int gradeId, string disStoreName, int orderTotalStart, int orderTotalEnd, long page, long itemsPerPage)
        {
            using (var db = new QDMallDatabase())
            {
                var sql = new StringBuilder();
                sql.Append("select * from dis_Distributor where 1=1 and isagent=1  AND isdelete=0");
                if (storeId > 0)
                    sql.AppendFormat(" and storeid={0}", storeId);
                if (gradeId > 0)
                    sql.AppendFormat(" and gradeid={0}", gradeId);
                if (orderTotalStart > 0)
                    sql.AppendFormat(" and OrdersTotal>={0}", orderTotalStart);
                if (orderTotalEnd > 0)
                    sql.AppendFormat(" and OrdersTotal<={0}", orderTotalEnd);
                if (!string.IsNullOrEmpty(disStoreName))
                    sql.AppendFormat(" and disstorename like '{0}%'", disStoreName);
                return db.Page<Distributor>(page, itemsPerPage, sql.ToString());
            }
        }
        /// <summary>
        /// 获取当前代理商下的所有分销商
        /// </summary>
        /// <param name="agentDId">代理商的主键ID</param>
        /// <param name="page"></param>
        /// <param name="itemsPerPage"></param>
        /// <returns></returns>
        public static Page<Distributor> GetAgentChildList(int dId, long page, long itemsPerPage)
        {
            using (var db = new QDMallDatabase())
            {
                return db.Page<Distributor>(page, itemsPerPage,
                    "select * from dis_Distributor where agentdid=@0 and isagent=0  AND isdelete=0", dId);
            }
        }

        /// <summary>
        /// 获取当前分销商下的所有分销商，包含一级和二级
        /// </summary>
        /// <param name="dId">分销商的主键ID</param>
        /// <param name="storeId">店铺ID</param>
        /// <param name="page"></param>
        /// <param name="itemsPerPage"></param>
        /// <returns></returns>
        public static Page<Distributor> GetDistributorChildList(int dId,int storeId, long page, long itemsPerPage)
        {
            using (var db = new QDMallDatabase())
            {
                var result= db.Page<Distributor>(page, itemsPerPage,
                    $"select * from dis_Distributor where ([Path] like '{dId}|%' or [Path] like '%|{dId}|') and isagent=0 and storeid={storeId}  AND isdelete=0");
                var items = result.Items;
                foreach (var item in items)
                {
                    item.DisLevel = 2;
                    if (item.Path.EndsWith($"{dId}|"))
                    {
                        item.DisLevel = 1;
                    }
                }
                result.Items = items;
                return result;
            }
        }
        #endregion

        public static void SyncUserInfo(int uid, string avatar, string nickName)
        {
            var dis = GetDistributorByUserId(uid);
            if (dis == null) return;
            dis.LinkMan = dis.DisStoreName = nickName;
            dis.ShowLogo = avatar;
            UpdateDistributor(dis);
        }
        /// <summary>
        /// 获取分销设置
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static DistributorSet GetDistriDisGradeSet(int storeid)
        {
            using (var db = new QDMallDatabase())
            {
                return db.SingleOrDefault<DistributorSet>("select  * from dis_Config where storeid=@0",storeid);
            }
        }
        

        public static void SetDistributorset(string CardSlogan,int storeid)
        {
            using (var db=new QDMallDatabase())
            {
                db.Execute("update dis_Config set CardSlogan=@0 where storeid=@1", CardSlogan, storeid);
            }
        }
        public static int AddDistributorset(DistributorSet distributorset)
        {
            using (var db = new QDMallDatabase())
            {
                var o = db.Insert(distributorset).ToString();
                var id = 0;
                int.TryParse(o, out id);
                return id;
            }
        }
    }
}
